package project.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import project.DAO.UserDAO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Objects;


@Controller
public class UserController {
    @Autowired
    UserDAO userDAO;

    @RequestMapping("/loginCheck")
    public String loginCheck(HttpServletRequest request, Map<String, String> map) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        HttpSession session = request.getSession();
        if (username == null && password == null) {
            map.put("error", "您还未登录");
            return "login";
        } else if (userDAO.login(username, password).size() == 0) {
            map.put("error", "用户名或密码错误");
            System.out.println("用户密码错误");
            return "login";
        } else {
            map.put("error", "您已成功登录");
            session.setAttribute("username", username);
            System.out.println("用户会话域存储的数据是" + session.getAttribute("username"));
            System.out.println(username);
            return "login";
        }


    }
    @RequestMapping("/prove")
    public String register(HttpServletRequest request, Map map) {
        HttpSession session = request.getSession();
        String  code1 = request.getParameter("code1");
        if (code1 !=null) {
            if(Objects.equals(code1, String.valueOf(session.getAttribute("code"))))
            {
                map.put("error", "您的验证已通过请您继续进行登录操作");
                userDAO.register(session.getAttribute("username"),session.getAttribute("password"));
            }
            else
            {
                map.put("error", "您的验证码输入错误");
            }
        }
        else{
            map.put("error","请输入验证码1");
        }
        return "prove";
    }
}



